package util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;

import entity.Customer;

public class FileHelper {

	private static StringBuilder sb;

	public static void write(Set<Customer> set, String format) throws IOException {

		// FileOutputStream o = null;
		FileOutputStream o = null;
		if (format.contains("xml")) {
			o = new FileOutputStream("cus.xml");
			o.write(printXML(set).getBytes());
		} else {
			o = new FileOutputStream("cus.txt");
			o.write(print(set).getBytes());
		}
		o.close();

	}

	public static String print(Set<Customer> set) {
		sb = new StringBuilder();
		for (Customer c : set) {
			System.out.println(c.getId() + "\t\t" + c.getName() + "\t\t" + c.getEmail() + "\t\t" + c.isSex() + "\t\t"
					+ c.getBirth());
			sb.append(c.getId() + "\t\t" + c.getName() + "\t\t" + c.getEmail() + "\t\t" + c.isSex() + "\t\t"
					+ c.getBirth() + "\r\n");
		}
		return sb.toString();
	}

	public static String printXML(Set<Customer> set) {
		sb = new StringBuilder();
		sb.append("<Customers>\r\n");
		for (Customer customer : set) {
			sb.append("\t<Customer id=\"" + customer.getId() + "\">\r\n")
					.append("\t\t<name>" + customer.getName() + "</name>\r\n")
					.append("\t\t<birth>" + customer.getBirth() + "</birth>\r\n")
					.append("\t\t<sex>" + customer.isSex() + "</sex>\r\n")
					.append("\t\t<email>" + customer.getEmail() + "</email>\r\n").append("\t</Customer>\r\n");
		}
		sb.append("</Customers>\r\n");
		System.out.println(sb.toString());
		return sb.toString();
	}

}
